import webapp2

from google.appengine.ext import db
import json

class ArduinoInfo(db.Model):
    """Models a data report from an arduino"""
    token = db.IntegerProperty()
    temperature = db.IntegerProperty()
    proximity = db.IntegerProperty()
    ambient = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class Token(db.Model):
    """Models a data report from an arduino"""
    value = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class MainHandler(webapp2.RequestHandler):
    def get(self):
        tokens = Token(value = 610526241).put()
        self.response.out.write('Hello world!')

class PostHandler(webapp2.RequestHandler):
    def post(self):
        data = json.loads(self.request.body)
        self.response.out.write(data)
        if('token' in data):
            g = Token.gql("WHERE value = :1", data['token'])
            if (g.count() > 0):
                info = ArduinoInfo(token = data['token'], temperature= data['temperature'],proximity = data['proximity'],ambient = data['ambient'])
                info.put();
            else:
                self.error(403) # access denied
                return
        else:
            self.error(403) # access denied
            return



app = webapp2.WSGIApplication([('/', MainHandler),('/rest', PostHandler)],
                             debug=True)

